package com.joey.sf.no1;


import org.junit.Assert;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Random;

/**
 * @author Joey Huang QQ:273179370
 * @create 2017/10/23
 */
public class No1_1 {

    public static void main(String[] args) {
        /*
        减法运算：
        比如
         0000...1011
        -0000...0011
        -------------
        =0000...1000

        过程：
            a. 去反码 0000...0011 =》 1111...1100
            b. 加1 1111...1100+1 =》 1111...1101
            c. 相加 0000...1011 + 1111...1101 = 0000...1000

        因此：
          -1 = 0000....0001 =》1111....1110 + 1 =》1111....1111

        Integer.MIN_VALUE = 1000.....0000
        -Integer.MIN_VALUE = -1000.....0000 =》0111....1111 + 1 =》1000....0000 =  Integer.MIN_VALUE
        */
        System.out.println(Integer.MIN_VALUE);
        System.out.println(Integer.MAX_VALUE);
        System.out.println(0 - Integer.MIN_VALUE);

        System.out.println(10 % -6);
        System.out.println(-10 % 6);
        System.out.println(2.0e-6 * 100000000.1);

        double t = 9.0;
        while (Math.abs(t - 9.0 / t) > .001)
            t = (9.0 / t + t) / 2.0;
        System.out.println(String.format("%.5f\n", t));
        System.out.println('b');
        System.out.println('b' + 'c');
        System.out.println('b' + "" + 'c');
        System.out.println((char) ('b' + 'c'));


    }

    /**
     * 二分查找
     * <p>
     * 前提：数组必须是有序
     */
    static int find1(int key, int[] arrays) {
        int start = 0;
        int end = arrays.length - 1;
        while (start <= end) {
            int mid = (start + end) / 2;
            if (arrays[mid] == key) {
                return mid;
            }
            if (arrays[mid] > key) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }
        return -1;
    }


    @Test
    public void testFind1() {
        int[] array = createInt(100_000);
        Arrays.sort(array);//排序

        for (int i = 0; i < 1000; i++) {
            int targetPosition = (int) (Math.random() * array.length);
            int position = find1(array[targetPosition], array);
            Assert.assertEquals(position, targetPosition);
        }
    }

    //生成不重复的随机数组
    private int[] createInt(int length) {
        int[] array = new int[length];
        for (int i = 0; i < length; i++) {
            if (i == 0) {
                array[i] = 1 + (int) (Math.random() * 5);
            } else {
                array[i] = array[i - 1] + 1 + (int) (Math.random() * 5);
            }
        }
        MathUtils.shuffle(array);
        return array;
    }
}
